package com.niiwoo.civet.mobile.controller.myloan;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.account.dto.common.UserAccountInfoDTO;
import com.niiwoo.civet.account.dto.response.AccountBaseResponse;
import com.niiwoo.civet.account.enums.AccountActiveEnum;
import com.niiwoo.civet.account.service.AccountDubboService;
import com.niiwoo.civet.account.service.AccountRefundOrderPushDubboService;
import com.niiwoo.civet.base.constant.OrgConstant;
import com.niiwoo.civet.mobile.util.MaskUtil;
import com.niiwoo.civet.mobile.vo.request.myloan.*;
import com.niiwoo.civet.mobile.vo.response.myloan.*;
import com.niiwoo.civet.mobile.vo.response.myloan.QueryRepaymentDynamicReponseVO.RepaymentDynamicVO;
import com.niiwoo.civet.mobile.vo.response.myloan.QueryRepaymentPlanReponseVO.RepaymentPlanVO;
import com.niiwoo.civet.mobile.vo.response.user.QueryProjectInfoResponseVO;
import com.niiwoo.civet.trade.dto.common.LoanBusinessInfoDTO;
import com.niiwoo.civet.trade.dto.common.ProjectDTO;
import com.niiwoo.civet.trade.dto.request.myloan.*;
import com.niiwoo.civet.trade.dto.response.NoviceInvestInfoResponseDTO;
import com.niiwoo.civet.trade.dto.response.myloan.*;
import com.niiwoo.civet.trade.dto.response.myloan.QueryRepaymentPlanResponseDTO.ProjectBorrowerPlanReponseDTO;
import com.niiwoo.civet.trade.enums.BorrowerTypeEnum;
import com.niiwoo.civet.trade.enums.ChannelCodeEnum;
import com.niiwoo.civet.trade.enums.LoanTypeForPrizeEnum;
import com.niiwoo.civet.trade.enums.ProjectTypeEnum;
import com.niiwoo.civet.trade.service.invest.InvestDubboService;
import com.niiwoo.civet.trade.service.loan.LoanBusinessDubboService;
import com.niiwoo.civet.trade.service.myloan.MyLoanDubboService;
import com.niiwoo.civet.trade.service.project.ProjectDubboService;
import com.niiwoo.civet.trade.service.refund.RepaymentDubboService;
import com.niiwoo.civet.user.dto.UserPersonalDubboInfoDTO;
import com.niiwoo.civet.user.dto.request.LoanDataAuthenticationRequestDTO;
import com.niiwoo.civet.user.dto.response.LoanDataAuthenticationResponseDTO;
import com.niiwoo.civet.user.dto.response.UserBasicInfoResponseDTO;
import com.niiwoo.civet.user.enums.UserPersonalEnum;
import com.niiwoo.civet.user.service.UserBasicInfoDubboService;
import com.niiwoo.civet.user.service.UserDataDubboService;
import com.niiwoo.civet.user.service.UserStatusDubboService;
import com.niiwoo.tripod.consumer.component.FileUploadHandler;
import com.niiwoo.tripod.consumer.properties.FileUploadProperties;
import com.niiwoo.tripod.consumer.util.FileMediaExtensions;
import com.niiwoo.tripod.consumer.util.ImageUploadUtil;
import com.niiwoo.tripod.lanmao.enums.UserRoleEnum;
import com.niiwoo.tripod.provider.dto.response.PageResponseDTO;
import com.niiwoo.tripod.web.annotation.AuthIgnore;
import com.niiwoo.tripod.web.util.PrincipalContext;
import com.niiwoo.tripod.web.vo.Empty;
import com.niiwoo.tripod.web.vo.PageRequestVO;
import com.niiwoo.tripod.web.vo.PageResponseVO;
import com.niiwoo.tripod.web.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;


@RestController
@RequestMapping("/myLoan")
@Api(tags = "我的借款: (付圣才,廖君君,宾村)")
@Slf4j
public class MyLoanController {

    @Reference(version = "1.0.0")
    private MyLoanDubboService myLoanDubboService;

    @Reference(version = "1.0.0")
    private AccountDubboService accountDubboService;

    @Reference(version = "1.0.0")
    private UserBasicInfoDubboService userBasicInfoDubboService;

    @Reference(version = "1.0.0")
    private AccountRefundOrderPushDubboService accountRefundOrderPushDubboService;

    @Reference(version = "1.0.0")
    private RepaymentDubboService repaymentDubboService;

    @Reference(version = "1.0.0")
    private UserStatusDubboService userStatusDubboService;

    @Reference(version = "1.0.0")
    private LoanBusinessDubboService loanBusinessDubboService;

    @Reference(version = "1.0.0")
    private UserDataDubboService userDataDubboService;

    @Reference(version = "1.0.0")
    private ProjectDubboService projectDubboService;

    @Autowired
    private FileUploadHandler fileUploadHandler;

    @Reference(version = "1.0.0")
    private InvestDubboService investDubboService;

    @Value("${h5-borrow-detail-url}")
    private String h5BorrowDetailUrl;

    @PostMapping("/loanIndexQuery")
    @ApiOperation("借款首页数据查询")
    public Result<LoanIndexQueryResponseVO> loanIndexQuery() {

        String userId = PrincipalContext.getUserId();
        // 先异步访问远程接口
        Future<UserBasicInfoResponseDTO> future = RpcContext.getContext().asyncCall(
                new Callable<UserBasicInfoResponseDTO>() {
                    @Override
                    public UserBasicInfoResponseDTO call() throws Exception {
                        return userBasicInfoDubboService.getUserBasicInfo(userId);
                    }
                });
        LoanIndexQueryResponseDTO dto = myLoanDubboService.loanIndexQuery(userId);
        dto.getCurrMonthRefundPlans().forEach(p -> {
            p.setWebUrl(h5BorrowDetailUrl + p.getProjectId());
        });
        LoanIndexQueryResponseVO vo = new LoanIndexQueryResponseVO();
        BeanUtils.copyProperties(dto, vo);

        try {
            vo.setHeadImage(future.get().getHeadImage());
        } catch (InterruptedException | ExecutionException e) {
            log.error("InterruptedException,ExecutionException ", e);
        }


        return Result.with(vo);
    }


    @PostMapping("/loanPlanDayQuery")
    @ApiOperation("还款计划-按日查看")
    public Result<PageResponseVO<LoanPlanDateResponseVO>> loanPlanDateQuery(@RequestBody PageRequestVO vo) {
        String userId = PrincipalContext.getUserId();

        MyloanRequestDTO dto = new MyloanRequestDTO();
        dto.setUserId(userId);
        dto.setPageNumber(vo.getPageNumber());
        dto.setPageSize(vo.getPageSize());


        PageResponseDTO<LoanPlanDateResponseDTO> resultDto = myLoanDubboService.loanPlanDateQuery(dto);
        PageResponseVO<LoanPlanDateResponseVO> resultVo = new PageResponseVO<>();
        resultVo.setTotalPage(resultDto.getTotalPage());
        resultVo.setTotalCount(resultDto.getTotalCount());
        List<LoanPlanDateResponseVO> list = new ArrayList<>();
        resultVo.setItems(list);
        resultDto.getItems().forEach(p -> {
            LoanPlanDateResponseVO loanPlanDateResponseVO = new LoanPlanDateResponseVO();
            loanPlanDateResponseVO.setYearMouth(p.getYearMouth().substring(0, 4) + "年" + p.getYearMouth().substring(4, p.getYearMouth().length()) + "月");
            List<LoanPlanDateResponseVO.LoanPlan> loanPlans = new ArrayList<>();
            loanPlanDateResponseVO.setLoanPlans(loanPlans);

            list.add(loanPlanDateResponseVO);
            p.getLoanPlans().forEach(h -> {
                LoanPlanDateResponseVO.LoanPlan plan = new LoanPlanDateResponseVO.LoanPlan();
                plan.setH5Url(h5BorrowDetailUrl + h.getProjectId());
                plan.setAmount(h.getAmount());
                plan.setProjectId(h.getProjectId());
                plan.setRefundDate(h.getRefundDate());

                loanPlans.add(plan);
            });
        });
        return Result.with(resultVo);
    }

    @PostMapping("/loanPlanMonthQuery")
    @ApiOperation("还款计划-按月查看")
    public Result<PageResponseVO<LoanPlanMonthResponseVO>> loanPlanMonthQuery(@RequestBody PageRequestVO vo) {
        String userId = PrincipalContext.getUserId();
        MyloanRequestDTO dto = new MyloanRequestDTO();
        dto.setUserId(userId);
        dto.setPageNumber(vo.getPageNumber());
        dto.setPageSize(vo.getPageSize());

        return Result.with(JSON.parseObject(JSON.toJSONString(myLoanDubboService.loanPlanMonthQuery(dto)),
                PageResponseVO.class));
    }

    @PostMapping("/myLoanGoingQuery")
    @ApiOperation("我的借款查询-进行中")
    public Result<PageResponseVO<MyloanGoingResponseVO>> myloanGoingQuery(@RequestBody PageRequestVO vo) {
        String userId = PrincipalContext.getUserId();
        MyloanRequestDTO dto = new MyloanRequestDTO();
        dto.setUserId(userId);
        dto.setPageNumber(vo.getPageNumber());
        dto.setPageSize(vo.getPageSize());

        PageResponseDTO<LoanGoingResponseDTO> resultDto = myLoanDubboService.myloanGoingQuery(dto);
        resultDto.getItems().forEach(p -> {
            p.setH5Url(h5BorrowDetailUrl + p.getProjectId());
        });
        return Result.with(JSON.parseObject(JSON.toJSONString(resultDto),
                PageResponseVO.class));
    }

    @PostMapping("/myLoanEndedQuery")
    @ApiOperation("我的借款查询-已结束")
    public Result<PageResponseVO<MyloanEndedResponseVO>> myloanEndedQuery(@RequestBody PageRequestVO vo) {
        String userId = PrincipalContext.getUserId();
        MyloanRequestDTO dto = new MyloanRequestDTO();
        dto.setUserId(userId);
        dto.setPageNumber(vo.getPageNumber());
        dto.setPageSize(vo.getPageSize());

        PageResponseDTO<LoanEndResponseDTO> resultDto = myLoanDubboService.myloanEndedQuery(dto);
        resultDto.getItems().forEach(p -> {
            p.setH5Url(h5BorrowDetailUrl + p.getProjectId());
        });

        return Result.with(JSON.parseObject(JSON.toJSONString(resultDto),
                PageResponseVO.class));
    }

    @PostMapping("/immediateRepayment")
    @ApiOperation("立即还款弹窗查询")
    public Result<ImmediateRepaymentResponseVO> immediateRepayment(@RequestBody @Valid ImmediateRepaymentRequestVO vo) {
		String userId = PrincipalContext.getUserId();
		ImmediateRepaymentResponseVO immediateRepaymentResponseVO = new ImmediateRepaymentResponseVO();

		ProjectDetailResponseDTO project = myLoanDubboService.queryProjectDetailByProjectId(vo.getProjectId());
		if (Objects.nonNull(project)) {
			immediateRepaymentResponseVO.setChannelCode(project.getChannelCode());
		}

		UserAccountInfoDTO userAccountInfoDTO = this.getAccount(userId, project.getOrgId());
		BeanUtils.copyProperties(userAccountInfoDTO, immediateRepaymentResponseVO);
		if (userAccountInfoDTO.getBorrowerActive().equals(AccountActiveEnum.UNACTIVATED.getValue())
				|| userAccountInfoDTO.getBorrowerActive().equals(AccountActiveEnum.NOT_OPEN.getValue())) {
			immediateRepaymentResponseVO.setBorrowerActive(userAccountInfoDTO.getBorrowerActive());
			//考拉的标不需要做存管验证
			if (!ChannelCodeEnum.KAOLA.getChanelCode().equals(immediateRepaymentResponseVO.getChannelCode())) {
				return Result.with(immediateRepaymentResponseVO);
			}

		}

        repaymentDubboService.checkRepaymentByProjectId(vo.getProjectId());

        MyProjectRequestDTO myProjectRequestDTO = new MyProjectRequestDTO();
        myProjectRequestDTO.setProjectId(vo.getProjectId());
        myProjectRequestDTO.setUserId(userId);
        //myProjectRequestDTO.setCurrentPeriod(vo.getCurrentPeriod());
        ImmediateRepaymentResponseDTO immediateRepaymentResponseDTO = myLoanDubboService
                .queryImmediateRepayment(myProjectRequestDTO);
        BeanUtils.copyProperties(immediateRepaymentResponseDTO, immediateRepaymentResponseVO);

        return Result.with(immediateRepaymentResponseVO);
    }

    @PostMapping("/contractQuery")
    @ApiOperation("我的借款-查看合同")
    public Result<ContractResponseVO> contractQuery(@RequestBody @Valid ContractRequestVO vo) {
        String userId = PrincipalContext.getUserId();
        MyProjectRequestDTO myProjectRequestDTO = new MyProjectRequestDTO();
        myProjectRequestDTO.setProjectId(vo.getProjectId());
        myProjectRequestDTO.setUserId(userId);
        return Result.with(JSON.parseObject(JSON.toJSONString(myLoanDubboService.contractQuery(myProjectRequestDTO)),
                ContractResponseVO.class));
    }


    @PostMapping("/projectBorrowDetail")
    @ApiOperation("借款详情页")
    public Result<ProjectBorrowDetailReponseVO> projectBorrowDetail(
            @RequestBody @Valid ProjectBorrowDetailRequestVO requestVO) {
        String userId = PrincipalContext.getUserId();
        log.info("projectBorrowDetail.userId={},requestVO={}",userId,JSON.toJSONString(requestVO));
        QueryProjectBorrowDetailReponseDTO dto = myLoanDubboService.queryProjectBorrowDetail(requestVO.getProjectId(), userId);

        // 是否显示提额
        dto.setShowIncreaseLoanAmount(false);
        if(dto.getTeProjectFlag().equals(Byte.valueOf("0"))){  //是否提额标的标识：0、否；1、是
            dto.setShowIncreaseLoanAmount(this.getShowIncreaseLoanAmount(userId, dto));
        }
        log.info("projectBorrowDetail.userId={},dto={}",userId,JSON.toJSONString(dto));
        return Result.with(JSON.parseObject(JSON.toJSONString(dto), ProjectBorrowDetailReponseVO.class));
    }

    /**
     * 是否显示提额认证
     */
    private boolean getShowIncreaseLoanAmount(String userId, QueryProjectBorrowDetailReponseDTO dto){
        LoanDataAuthenticationRequestDTO loanData = new LoanDataAuthenticationRequestDTO();
        loanData.setUserId(userId);

        LoanDataAuthenticationResponseDTO responseDTO = userDataDubboService.loanDataAuthentication(loanData);
        log.info("getShowIncreaseLoanAmount LoanDataAuthenticationResponseDTO={}", JSON.toJSONString(responseDTO));
        LoanBusinessInfoDTO loanBusinessInfoDTO = loanBusinessDubboService.selectByProductType(ProjectTypeEnum.getEnum(dto.getType()).getValue());
        if(loanBusinessInfoDTO == null){
            return false;
        }

        boolean educationAuth = false;
        boolean jdAuth = false;
        boolean creditCardAuth = false;
        boolean socialSecurityAuth = false;
        ProjectDTO projectDTO = projectDubboService.selectProjectById(dto.getProjectId());
        UserPersonalDubboInfoDTO personalInfo = null;
        try {
            personalInfo = userDataDubboService.userPersonalInfo(userId);
        } catch (Exception e){
            log.info("userPersonalInfo Exception:",e);
            throw e;
        }

        if(loanBusinessInfoDTO.getEduAuth() == 1
                && !UserPersonalEnum.UserEduLevelEnum.SPECIAL_SCHOOL.getType().equals(personalInfo.getEducationLevel())){
            if(responseDTO.getEducationAuthorize() != 1 && responseDTO.getEducationAuthorize() != 2){
                educationAuth = true;
            }
            if((responseDTO.getEducationAuthorize() == 1 || responseDTO.getEducationAuthorize() == 2)
                    && projectDTO.getCreateTime().before(responseDTO.getEducationTime())){
                educationAuth = true;
            }
        }

        if(loanBusinessInfoDTO.getJdAuth() == 1){
            if(responseDTO.getJdAuthorize() != 1 && responseDTO.getJdAuthorize() != 2){
                jdAuth = true;
            }
            if((responseDTO.getJdAuthorize() == 1 || responseDTO.getJdAuthorize() == 2)
                    && projectDTO.getCreateTime().before(responseDTO.getJdAuthTime())){
                jdAuth = true;
            }
        }

        if(loanBusinessInfoDTO.getCreditCardAuth() == 1){
            if(responseDTO.getCreditCardAuthorize() != 1 && responseDTO.getCreditCardAuthorize() != 2){
                creditCardAuth = true;
            }
            if((responseDTO.getCreditCardAuthorize() == 1 || responseDTO.getCreditCardAuthorize() == 2)
                    && projectDTO.getCreateTime().before(responseDTO.getCreditCardTime())){
                creditCardAuth = true;
            }
        }

        if(loanBusinessInfoDTO.getSocialSecurityAuth() == 1){
            if(responseDTO.getSocialSecurityOperatorAuthorize() != 1 && responseDTO.getSocialSecurityOperatorAuthorize() != 2){
                socialSecurityAuth = true;
            }
            if((responseDTO.getSocialSecurityOperatorAuthorize() == 1 || responseDTO.getSocialSecurityOperatorAuthorize() == 2)
                    && projectDTO.getCreateTime().before(responseDTO.getSocialSecurityTime())){
                socialSecurityAuth = true;
            }
        }

        return educationAuth || jdAuth || creditCardAuth || socialSecurityAuth;
    }

    @PostMapping("/projectBorrowDetailAPP")
    @ApiOperation("借款详情页-APP")
    public Result<ProjectBorrowDetailAPPReponseVO> projectBorrowDetailAPP(
            @RequestBody @Valid ProjectBorrowDetailRequestVO requestVO) {
        String userId = PrincipalContext.getUserId();
        // 先异步访问远程接口
        Future<UserBasicInfoResponseDTO> future = RpcContext.getContext().asyncCall(
                new Callable<UserBasicInfoResponseDTO>() {
                    @Override
                    public UserBasicInfoResponseDTO call() throws Exception {
                        return userBasicInfoDubboService.getUserBasicInfo(userId);
                    }
                });

        QueryProjectBorrowDetailAPPReponseDTO dto = myLoanDubboService.queryProjectBorrowDetailAPP(requestVO.getProjectId(),
                userId);
        ProjectBorrowDetailAPPReponseVO reponseVO = JSON.parseObject(JSON.toJSONString(dto),
                ProjectBorrowDetailAPPReponseVO.class);

        try {
            UserBasicInfoResponseDTO userBasicInfoResponseDTO = future.get();

            reponseVO.setNickName(userBasicInfoResponseDTO.getNickName());
            reponseVO.setHeadImage(userBasicInfoResponseDTO.getHeadImage());
        } catch (InterruptedException e) {
            log.error("", e);
        } catch (ExecutionException e) {
            log.error("", e);
        }

        return Result.with(reponseVO);
    }

    @PostMapping("/queryFullAmountRepayment")
    @ApiOperation("提前结清弹窗")
    public Result<QueryFullAmountRepaymentReponseVO> queryFullAmountRepayment(
            @RequestBody @Valid QueryFullAmountRepaymentRequestVO requestVO) {
        String userId = PrincipalContext.getUserId();
        QueryFullAmountRepaymentReponseVO reponseVO = new QueryFullAmountRepaymentReponseVO();
        ProjectDetailResponseDTO project = myLoanDubboService.queryProjectDetailByProjectId(requestVO.getProjectId());
		if (Objects.nonNull(project)) {
			reponseVO.setChannelCode(project.getChannelCode());
		}
		UserAccountInfoDTO userAccountInfoDTO = this.getAccount(userId,project.getOrgId());
        BeanUtils.copyProperties(userAccountInfoDTO, reponseVO);

        if (userAccountInfoDTO.getBorrowerActive().equals(AccountActiveEnum.UNACTIVATED.getValue())
                || userAccountInfoDTO.getBorrowerActive().equals(AccountActiveEnum.NOT_OPEN.getValue())) {
            reponseVO.setBorrowerActive(userAccountInfoDTO.getBorrowerActive());
        	//考拉的标不需要做存管验证
			if (!ChannelCodeEnum.KAOLA.getChanelCode().equals(reponseVO.getChannelCode())) {
				return Result.with(reponseVO);
			}
            
        }
        QueryFullAmountRepaymentReponseDTO dto = myLoanDubboService.queryFullAmountRepayment(requestVO.getProjectId(),
                userId);
        BeanUtils.copyProperties(dto, reponseVO);
        return Result.with(reponseVO);
    }

    private UserAccountInfoDTO getAccount(String userId,String orgId) {
    	UserAccountInfoDTO accountInfoDTO = new UserAccountInfoDTO();
    	AccountBaseResponse borrowAccount = null; 
    	AccountBaseResponse investorAccount = null;
    	if(OrgConstant.NIIWOO_ORG_ID.equals(orgId)) {
    		borrowAccount = accountDubboService.getNiiwooAccount(userId, UserRoleEnum.BORROWERS);
    		investorAccount=accountDubboService.getNiiwooAccount(userId, UserRoleEnum.INVESTOR);
    	}else {
    		borrowAccount = accountDubboService.getOrgAccount(userId, orgId);
    	}
    	if(Objects.nonNull(borrowAccount)) {
    		accountInfoDTO.setAccountNoBorrower(borrowAccount.getAccountNo());
    		accountInfoDTO.setBorrowerActive(borrowAccount.getImportUserActiva());
    		accountInfoDTO.setBalanceAmountBorrower(borrowAccount.getAvailableAmount());
    	}
    	if(Objects.nonNull(investorAccount) ) {
    		accountInfoDTO.setIsFreeInvest(investorAccount.getTender());
    		accountInfoDTO.setAccountNoInvestor(investorAccount.getAccountNo());
    		accountInfoDTO.setInvestorActive(investorAccount.getImportUserActiva());
    		accountInfoDTO.setBalanceAmountInvestor(investorAccount.getAvailableAmount());
    	}
    	return accountInfoDTO;
    }
    
    @PostMapping("/queryRepaymentPlan")
    @ApiOperation("查询还款安排")
    public Result<QueryRepaymentPlanReponseVO> queryRepaymentPlan(
            @RequestBody @Valid QueryRepaymentPlanRequestVO requestVO) {
        String userId = PrincipalContext.getUserId();
        QueryRepaymentPlanReponseVO reponseVO = new QueryRepaymentPlanReponseVO();
        QueryRepaymentPlanResponseDTO dto = myLoanDubboService.queryRepaymentPlan(requestVO.getProjectId(), userId);
        if (dto != null) {
            reponseVO.setRepaymentType(dto.getRepaymentType());

            List<RepaymentPlanVO> repayMentPlanVOList = new ArrayList<>();
            List<ProjectBorrowerPlanReponseDTO> borrowerPlanReponseDTOList = dto.getBorrowerPlanReponseDTOList();
            for (ProjectBorrowerPlanReponseDTO projectBorrowerPlanReponseDTO : borrowerPlanReponseDTOList) {
                RepaymentPlanVO repaymentPlanVO = new RepaymentPlanVO();

                BeanUtils.copyProperties(projectBorrowerPlanReponseDTO, repaymentPlanVO);
                repayMentPlanVOList.add(repaymentPlanVO);
            }

            reponseVO.setRepayMentPlanVOList(repayMentPlanVOList);
        }
        return Result.with(reponseVO);
    }

    @PostMapping("/queryRepaymentDynamic")
    @ApiOperation("查询还款记录")
    public Result<QueryRepaymentDynamicReponseVO> queryRepaymentDynamic(
            @RequestBody @Valid QueryRepaymentDynamicRequestVO requestVO) {
        String userId = PrincipalContext.getUserId();
        QueryRepaymentDynamicReponseVO reponseVO = new QueryRepaymentDynamicReponseVO();
        QueryProjectDynamicReponseDTO dto = myLoanDubboService.queryProjectDynamic(requestVO.getProjectId(), userId);
        if (dto != null) {
            reponseVO.setProjectId(dto.getProjectId());

            List<RepaymentDynamicVO> repaymentDynamicVOList = new ArrayList<>();
            List<ProjectDynamicReponseDTO> projectDynamicReponseDTOList = dto.getProjectDynamicReponseDTOList();
            for (ProjectDynamicReponseDTO projectDynamicReponseDTO : projectDynamicReponseDTOList) {
                RepaymentDynamicVO repaymentDynamicVO = new RepaymentDynamicVO();

                BeanUtils.copyProperties(projectDynamicReponseDTO, repaymentDynamicVO);
                repaymentDynamicVOList.add(repaymentDynamicVO);
            }

            reponseVO.setRepaymentDynamicVOList(repaymentDynamicVOList);
        }
        return Result.with(reponseVO);
    }

    @PostMapping("/cancelProject")
    @ApiOperation("取消借款")
    public Empty cancelProject(@RequestBody @Valid CancelProjectRequestVO requestVO) {
        log.info("cancelProject.requestVO={}", JSON.toJSONString(requestVO));
        String userId = PrincipalContext.getUserId();
        log.info("cancelProject.userId={}", userId);
        //String userId =  String.valueOf(PrincipalContext.getUserId());
        LoanProjectRequestDTO dto = new LoanProjectRequestDTO();
        dto.setProjectId(requestVO.getProjectId());
        dto.setUserId(userId);
        String cancerReason = requestVO.getCancerReason();
        cancerReason = StringUtils.hasText(cancerReason) ? cancerReason : "手动取消借款";
        dto.setRemark(cancerReason);
        myLoanDubboService.cancelProject(dto);
        log.info("cancelProject.userId={} end", userId);
        return Empty.getInstance();
    }

    @PostMapping("/publishProject")
    @ApiOperation("发布借款（作废，不可用）")
    public Empty publishProject(@RequestBody @Valid PublishProjectRequestVO requestVO) {
        /*String userId = PrincipalContext.getUserId();
        LoanProjectRequestDTO dto = new LoanProjectRequestDTO();
        dto.setProjectId(requestVO.getProjectId());
        dto.setUserId(userId);
        Integer status = myLoanDubboService.publishProject(dto);
        PublishProjectResponseVO responseVO = new PublishProjectResponseVO();
        responseVO.setSubStatus(status);
        responseVO.setStatus(ProjectSubStatusEnum.enumOf(status).getParentStatusEnum().getStatus());*/
        return Empty.getInstance();
    }

    @AuthIgnore
    @PostMapping("/queryProjectInfoDetail")
    @ApiOperation("标的详情查询")
    public Result<QueryProjectInfoResponseVO> queryProjectInfoDetail(@RequestBody @Valid ProjectBorrowDetailRequestVO requestVO) {
        String userId = PrincipalContext.getUserId();
        //String userId = "aae20468-47f4-4f5d-bf48-507e9dabd1a1";
        MyProjectRequestDTO dto = new MyProjectRequestDTO();
        dto.setProjectId(requestVO.getProjectId());
        dto.setUserId(userId);
        UserProjectStatisticResponseDTO userProjectStatisticResponseDTO = myLoanDubboService.queryProjectInfoDetail(dto);

        QueryProjectInfoResponseVO queryProjectInfoResponseVO = JSON.parseObject(JSON.toJSONString(userProjectStatisticResponseDTO), QueryProjectInfoResponseVO.class);
        if (queryProjectInfoResponseVO != null) {
            if (BorrowerTypeEnum.COMPANY.getType().equals(queryProjectInfoResponseVO.getBorrowerType())) {
                queryProjectInfoResponseVO.setNickName(MaskUtil.maskCompanyName(queryProjectInfoResponseVO.getNickName()));
            }
            if (queryProjectInfoResponseVO.getProjectType() == 11) {
                queryProjectInfoResponseVO.setUserPrizeSuitProjectType(LoanTypeForPrizeEnum.enumOf(userProjectStatisticResponseDTO.getLoanType()).getUserPrizeSuitProjectType());
            } else {
                queryProjectInfoResponseVO.setUserPrizeSuitProjectType(ProjectTypeEnum.getEnum(userProjectStatisticResponseDTO.getProjectType()).getUserPrizeSuitProjectType());
            }

        }

        //判断是不是新手投
        NoviceInvestInfoResponseDTO responseDTO = investDubboService.getNoviceInvestInfos(userId,userProjectStatisticResponseDTO.getChannelCode());
        if (responseDTO.getIsNewProject() == (byte)1) {
            queryProjectInfoResponseVO.setIsNovice(responseDTO.getIsNovice());
            queryProjectInfoResponseVO.setRoleDefinitionDays(responseDTO.getRoleDefinitionDays());
            queryProjectInfoResponseVO.setNoviceSurplusInvestMoney(responseDTO.getNoviceSurplusInvestMoney());
        }
        return Result.with(queryProjectInfoResponseVO);
    }

    @PostMapping("/loanVoucherAuditInfoQuery")
    @ApiOperation("借款凭证查询")
    public Result<LoanVoucherAuditInfoQueryResponseVO> loanVoucherAuditInfoQuery(@RequestBody @Valid LoanVoucherAuditInfoQueryRequestVO requestVO) {
        log.info("loanVoucherAuditInfoQuery.requestVO={}",JSON.toJSONString(requestVO));
        String userId = PrincipalContext.getUserId();
        log.info("loanVoucherAuditInfoQuery.userId={}",userId);
        LoanVoucherAuditInfoQueryRequestDTO requestDTO = new LoanVoucherAuditInfoQueryRequestDTO();
        requestDTO.setBorrowUserId(requestVO.getBorrowUserId());
        requestDTO.setLoginUserId(userId);
        requestDTO.setProjectId(requestVO.getProjectId());
        LoanVoucherAuditInfoQueryResponseDTO responseDTO = myLoanDubboService.loanVoucherAuditInfoQuery(requestDTO);
        String jsonString = JSON.toJSONString(responseDTO);
        log.info("loanVoucherAuditInfoQuery.userId={},responseDTO={}",userId,JSON.toJSONString(jsonString));
        if(responseDTO==null){
            return Result.with( new LoanVoucherAuditInfoQueryResponseVO());
        }
        LoanVoucherAuditInfoQueryResponseVO responseVO = JSON.parseObject(jsonString,LoanVoucherAuditInfoQueryResponseVO.class);
        return Result.with(responseVO);
    }

    @PostMapping("/loanVoucherSubmit")
    @ApiOperation("借款凭证提交")
    public Empty loanVoucherSubmit(@RequestBody @Valid LoanVoucherSubmitRequestVO requestVO) {
        log.info("loanVoucherSubmit.requestVO={}",JSON.toJSONString(requestVO));
        String userId = PrincipalContext.getUserId();
        log.info("loanVoucherSubmit.userId={}",userId);
        LoanVoucherSubmitRequestDTO requestDTO = new LoanVoucherSubmitRequestDTO();
        requestDTO.setUserId(userId);
        requestDTO.setProjectId(requestVO.getProjectId());
        requestDTO.setLoanDesc(requestDTO.getLoanDesc());
        List<LoanVoucherSubmitRequestDTO.LoanVoucherImgRequestDTO> loanVoucherImgList = new ArrayList<>();
        requestVO.getLoanVoucherImgList().forEach(imgVO->{
            LoanVoucherSubmitRequestDTO.LoanVoucherImgRequestDTO imgDTO = new LoanVoucherSubmitRequestDTO.LoanVoucherImgRequestDTO();
            imgDTO.setImgUrl(imgVO.getImgUrl());
            imgDTO.setImgThumbnailUrl(imgVO.getImgThumbnailUrl());
            loanVoucherImgList.add(imgDTO);
        });
        requestDTO.setLoanVoucherImgList(loanVoucherImgList);
        myLoanDubboService.loanVoucherSubmit(requestDTO);
        log.info("loanVoucherSubmit.userId={} success",userId);
        return Empty.getInstance();
    }

    @PostMapping("/loanVoucherImgUpload")
    @ApiOperation("借款凭证图片上传")
    public Result<LoanVoucherImgUploadResponseVO> loanVoucherImgUpload(@RequestBody @Valid LoanVoucherImgUploadRequestVO requestVO) {
        String userId = PrincipalContext.getUserId();
        String imgContent = requestVO.getImgContent();
        log.info("loanVoucherSubmit.userId={},imgContent.size={}",userId,StringUtils.hasText(imgContent)?imgContent.length():0);

        LoanVoucherImgUploadResponseVO responseVO = new LoanVoucherImgUploadResponseVO();
        FileUploadProperties.FileUploadResult headImage;
        /*if (!fileUploadHandler.checkImageUploadMaxSize(headImageRequestVO.getHeadImage())) {
            log.error("图片大小不能超过5M：{}" + headImageRequestVO.getHeadImage());
            throw new BizException("USR10017");
        }*/
        if (!ImageUploadUtil.checkType(FileMediaExtensions.parseMediaExtension(imgContent))) {
            headImage = fileUploadHandler.upload(imgContent, true, "jpg");
        } else {
            headImage = fileUploadHandler.upload(imgContent, true);
        }

        responseVO.setImgUrl(headImage.getImageUrl());
        responseVO.setImgThumbnailUrl(headImage.getSmallImageUrl());

        log.info("loanVoucherSubmit.userId={} success",userId);
        return Result.with(responseVO);
    }
}
